<?php

namespace common\widgets\grid;

use Yii;
use common\helpers\Html;
use common\helpers\ArrayHelper;

/**
 * ActionColumn is a column for the [[GridView]] widget that displays buttons for viewing and manipulating the items.
 *
 * @author emhome <emhome@163.com>
 * @since 2.0
 */
class ActionColumn extends \yii\grid\ActionColumn {

    /**
     * @inheritdoc
     */
    public $header = '操作';

    /**
     * @inheritdoc
     */
    public $headerOptions = ['class' => 'action-column text-right'];

    /**
     * @inheritdoc
     */
    public $contentOptions = ['class' => 'button-column'];

    /**
     * @inheritdoc
     */
    public $buttonOptions = ['class' => 'btn btn-sm'];
    public $confirmDeleteTips = null;
    public $updateTag = null;

    /**
     * @inheritdoc
     */
    protected function initDefaultButtons() {
        $this->initDefaultButton('view', 'info');
        $this->initDefaultButton('update', 'warning');
        $this->initDefaultButton('delete', 'dark', [
            'data-confirm' => $this->confirmDeleteTips ?: Yii::t('yii', 'Are you sure you want to delete this item?'),
            'data-method' => 'post',
        ]);
    }

    /**
     * @inheritdoc
     */
    protected function initDefaultButton($name, $className, $additionalOptions = []) {
        if (!isset($this->buttons[$name]) && strpos($this->template, '{' . $name . '}') !== false) {
            $this->buttons[$name] = function ($url, $model, $key) use ($name, $className, $additionalOptions) {
                switch ($name) {
                    case 'view':
                        $title = Yii::t('yii', 'View');
                        break;
                    case 'update':
                        $title = '修改';
                        $className .= ' ' . $this->updateTag;
                        break;
                    case 'delete':
                        $title = Yii::t('yii', 'Delete');
                        break;
                    default:
                        $title = ucfirst($name);
                }
                $options = $this->loadAdditionalOptions($title, $className, $additionalOptions);
                $tag = ArrayHelper::remove($options, 'tag', 'a');
                return Html::$tag($title, $url, $options);
            };
        }
    }

    /**
     * @inheritdoc
     */
    protected function renderDataCellContent($model, $key, $index) {
        return preg_replace_callback('/\\{([^}]+)\\}/', function ($matches) use ($model, $key, $index) {
            $matchData = array_pad(explode(':', $matches[1] . ':'), 3, '');
            list($name, $title, $className) = $matchData;
            if (!$title) {
                $title = Yii::t('yii', ucfirst($name));
            }
            if (!$className) {
                $className = 'secondary';
            }
            if (isset($this->visibleButtons[$name])) {
                $isVisible = $this->visibleButtons[$name] instanceof \Closure ? call_user_func($this->visibleButtons[$name], $model, $key, $index) : $this->visibleButtons[$name];
                if (!$isVisible) {
                    return '';
                }
            }
            $url = $this->createUrl($name, $model, $key, $index);
            if (isset($this->buttons[$name])) {
                return call_user_func($this->buttons[$name], $url, $model, $key);
            }
            $options = $this->loadAdditionalOptions($title, $className);
            $tag = ArrayHelper::remove($options, 'tag', 'a');
            return Html::$tag($title, $url, $options);
        }, $this->template);
    }

    protected function loadAdditionalOptions($title, $className, $additionalOptions = []) {
        $options = array_merge([
            'title' => $title,
            'aria-label' => $title,
            'data-pjax' => 0,
            'tag' => 'a',
        ], $additionalOptions, $this->buttonOptions);

        $classes = [];
        if ($className) {
            if (is_string($className)) {
                $classes = preg_split('/\s+|[,|;]+/', $className, -1, PREG_SPLIT_NO_EMPTY);
            } elseif (is_array($className)) {
                $classes = $className;
            }
        }
        if (!empty($classes)) {
            foreach ($classes as $key => $class) {
                if ($class == 'modal') {
                    $options['tag'] = 'ajaxModal';
                    unset($classes[$key]);
                    $classes[$key] = 'btn-outline-warning';
                } elseif (in_array($class, ['primary', 'secondary', 'info', 'success', 'danger', 'warning', 'dark'])) {
                    $classes[$key] = 'btn-outline-' . $class;
                }
            }
        }
        Html::addCssClass($options, $classes);
        return $options;
    }

}
